package com.csy.crud.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author CSY
 * @date 2025 - 02 - 26
 */
public class DruidUtil {
    /**
     * 数据源对象
     */
    private static DataSource dataSource;

    /**
     * 获取数据源对象
     * @return 数据源对象
     */
    public static DataSource getDataSource(){
        if(dataSource == null){
            initDataSource();
        }
        return dataSource;
    }

    /**
     *初始化数据源对象
     */
    public static void initDataSource(){
        Properties prop = new Properties();
        try {
            prop.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取连接对象
     * @return 连接对象
     */
    public static Connection getConnection(){
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭连接（回收连接）
     * @param conn 连接对象
     */
    public static  void close(Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
